import { User } from '../models/user.model';
import { users } from '../mock/user.mock';

export class UserService {
    async login(username: string, password: string): Promise<User | null> {
        const user = users.find(u => u.username === username && u.password === password);
        if (!user) return null;
        const { password: _, ...userWithoutPassword } = user;
        return userWithoutPassword as User;
    }

    async register(userData: Omit<User, 'id'>): Promise<User | null> {
        // 检查用户名是否已存在
        if (users.some(u => u.username === userData.username)) {
            return null;
        }

        const newUser = {
            id: users.length + 1,
            ...userData
        };

        users.push(newUser);
        
        const { password: _, ...userWithoutPassword } = newUser;
        return userWithoutPassword as User;
    }

    async getUserInfo(userId: number): Promise<User | null> {
        const user = users.find(u => u.id === userId);
        if (!user) return null;
        const { password: _, ...userWithoutPassword } = user;
        return userWithoutPassword as User;
    }

    async updateUserInfo(userId: number, updateData: Partial<User>): Promise<User | null> {
        const userIndex = users.findIndex(u => u.id === userId);
        if (userIndex === -1) return null;

        // 不允许更新id和password
        const { id, password, ...allowedUpdates } = updateData;
        
        users[userIndex] = {
            ...users[userIndex],
            ...allowedUpdates
        };

        const { password: _, ...userWithoutPassword } = users[userIndex];
        return userWithoutPassword as User;
    }
}
